<template>
  <view class="pile-details">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="终端详情"></van-nav-bar>
    <!-- #endif -->
    <view class="pile-details-cnt">
      <!-- 顶部背景 -->
      <view class="header-bg"></view>
      <view class="header-bg bg-img"></view>
      <!-- 终端名称 -->
      <view class="header-wrap">
        <view class="name text-overflow">{{ data.items.connectorName }}</view>
        <view v-if="appType !== 'lznt'" class="number">{{ data.items.connectorCode }}</view>
        <view v-else class="number">快捷码：{{ data.items.shortcutCode }}</view>
      </view>
      <!-- 终端信息 -->
      <view class="info-wrap">
        <view class="flex-column info-row">
          <view class="textt">终端功率</view>
          <view class="textb">
            <text class="icon">{{ data.items.type === 1 ? '直' : '交' }}</text>
            {{ data.items.power }}kW
          </view>
        </view>
        <view class="flex-column row info-row">
          <view class="textt">工作电压</view>
          <view class="textb">{{ data.items.maxv }}V</view>
        </view>
        <view class="flex-column row info-row">
          <view class="textt">工作电流</view>
          <view class="textb">{{ data.items.maxa }}A</view>
        </view>
      </view>
      <!-- 其他信息 -->
      <view class="other-wrap flex-column" :style="styleOther">
        <view class="tilte text-bold">其他信息</view>
        <view v-for="item in data.prices" :key="item.id">
          <view class="row-wrap">
            <view class="textl">{{ item.title }}</view>
            <view class="text textr">
              <text v-if="item.deleteSumPrice" class="textr1">{{ item.deleteSumPrice }}</text>
              {{ item.sumPrice || '--' }}
            </view>
          </view>
          <view class="row-wrap">
            <view class="text">
              <text class="iconfont icon-power"></text>
              电费
            </view>
            <view class="text textr">
              <text v-if="item.deletePricePower" class="textr1">{{ item.deletePricePower }}</text>
              {{ item.pricePower || '--' }}
            </view>
          </view>
          <view class="row-wrap">
            <view class="text">
              <text class="iconfont icon-service"></text>
              服务费
            </view>
            <view class="text textr">
              <text v-if="item.deletePriceService" class="textr1">
                {{ item.deletePriceService }}
              </text>
              {{ item.priceService || '--' }}
            </view>
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="bottom-wrap text-bold" :style="styleBntH">
        <view class="text-wrap">
          单价：
          <text class="text">{{ data.sumPrice }}</text>
        </view>
        <button
          class="bnt-wrap bnt"
          @tap="tabCharge"
          :disabled="Boolean(data.items.workStatus === 3)">
          开始充电
        </button>
      </view>
    </view>
    <DialogOccupy ref="dialogOccupyRef" @start-charge="startCharge"></DialogOccupy>
  </view>
</template>

<script lang="ts" setup>
import DialogOccupy from '@/pages/charge/dialogOccupy.vue';
import {
  getSystemInfo,
  getToken,
  getUserId,
  setOrderObj,
  setToastInstance,
  systemInfo,
} from '@mixins/info';
import { queryConnector, queryStartCharge, getAccount } from '@/service/apis/station';
import { getUserCurrentOrder } from '@/service/apis/order';
import { getPrice } from './price';
import { noMultipleClicks } from '@/utils/util';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const appType = import.meta.env.VITE_VUE_APP_TYPE;

const $toast: any = inject('$Toast');

const styleBntH = `height: calc(124rpx - 36rpx + ${getSystemInfo().safeBottom}px)`;
let styleOther = ref(
  `height: calc(100vh - (124rpx - 36rpx + ${
    getSystemInfo().safeBottom
  }px) - 258rpx - 70rpx - 128rpx)`
);

// #ifdef H5
styleOther.value = `height: calc(100vh - (124rpx - 36rpx + ${
  getSystemInfo().safeBottom
}px) - 258rpx - 70rpx - 128rpx - ${getSystemInfo().navHeight}px)`;

// #endif

const dialogOccupyRef = ref();

const data = reactive({
  id: '',
  items: {} as any,
  prices: [] as any,
  sumPrice: '',
  msg: '',
  money: '',
});

onLoad((option: any) => {
  data.id = option.id;

  tabCharge = noMultipleClicks(tabCharge);
});

onShow(() => {
  queryConnector({
    id: data.id,
  }).then((res: any) => {
    data.items = res;
    data.prices = [];
    res?.appCostTemplateResultDTOList?.forEach((item: any) => {
      const obj = getPrice(item);
      data.prices.push(obj);
      if (item.nowFrame === 1) {
        data.sumPrice = obj.sumPrice;
      }
    });
  });
  const userId = getUserId();
  if (userId) {
    getAccount({ accountType: '0', originalAccountId: userId }).then((res: any) => {
      const money = Number(res.personalBalance) + Number(res.unitBalance);
      data.money = money.toFixed(2);
    });
  }
});

// 充值
const tabRecharge = () => {
  uni.navigateTo({
    url: `/pagesMyCenter/recharge/recharge`,
  });
};

// 开始充电
let tabCharge = () => {
  const token = getToken();
  if (!token) {
    uni.navigateTo({
      url: `/pages/login/login?page=/pages/stationDetails/pileDetails`,
    });
    return;
  }
  if (appType === 'lznt') {
    if (Number(data.money) >= 30) {
      startCharge();
    } else {
      uni.showModal({
        content: '尊敬的客户，您账户余额已不足30元，请及时充值，以免因余额不足而充电跳枪。',
        showCancel: true,
        cancelText: '继续充电',
        confirmText: '去充值',
        success: (e: any) => {
          if (e.confirm) {
            tabRecharge();
          } else if (e.cancel) {
            startCharge();
          }
        },
      });
    }
  } else {
    if (data.items.isOccupationCost) {
      dialogOccupyRef.value.open(data.items);
    } else {
      startCharge();
    }
  }
};
const startCharge = () => {
  queryStartCharge({
    userId: getUserId(),
    terminalId: data.id,
    chargeSource: '1',
    // #ifdef MP-WEIXIN
    chargeType: '1',
    // #endif
    // #ifdef MP-ALIPAY
    // @ts-ignore
    chargeType: '2',
    // #endif
    // #ifdef H5
    // @ts-ignore
    chargeType: '6',
    // #endif
  })
    .then((res: any) => {
      console.log('dddd---', res);
      uni.redirectTo({
        url: `/pages/charge/charging?id=${res.data}`,
      });
    })
    .catch((res: any) => {
      console.log('fff---', res);
      // 余额不足
      if (res.businessCode === '20102') {
        uni.showModal({
          content: res.msg,
          showCancel: false,
          success: () => {
            uni.navigateTo({
              url: `/pagesMyCenter/recharge/recharge`,
            });
          },
        });
      }
      //充电中订单
      else if (res.businessCode === '40401') {
        uni.showModal({
          content: res.msg,
          showCancel: true,
          success: (e: any) => {
            if (e.confirm) {
              // uni.switchTab({
              //   url: '/pages/order/order',
              // });
              const userId = getUserId();
              getUserCurrentOrder(userId).then((res1: any) => {
                if (res1) {
                  uni.redirectTo({
                    url: `/pages/charge/charging?id=${res1}`,
                  });
                } else {
                  $toast('充电订单已结束！');
                }
              });
            }
          },
        });
      }
      // 待支付订单
      else if (res.businessCode === '40403') {
        uni.showModal({
          content: res.msg,
          showCancel: false,
          success: () => {
            setOrderObj({ pageType: 'unpay' });
            uni.reLaunch({
              url: '/pages/order/order',
            });
          },
        });
      } else {
        $toast(res.msg);
      }
    });
};
// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
.pile-details {
  position: relative;
  width: 100vw;
  background: #f2f2f2;
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
  &-cnt {
    position: relative;
    width: 100vw;
    background: #f2f2f2;
  }

  .header-bg {
    position: absolute;
    width: 100%;
    height: 129px;
    top: 0;
    left: 0;
    background-image: linear-gradient(#5073f7, #2e52db);

    &.bg-img {
      background-image: url($url + 'station/pile-details.png');
      background-size: 100%;
      background-repeat: no-repeat;
    }
  }

  .header-wrap {
    position: relative;

    .name {
      padding: 24px 16px 0 16px;
      line-height: 28px;
      font-size: 20px;
      color: #fff;
    }

    .number {
      padding: 8px 16px 0 16px;
      line-height: 26px;
      font-size: 14px;
      color: #fff;
    }
  }

  .info-wrap {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 70px;
    margin: 16px;
    background: #fff;
    border-radius: 10px;

    .info-row {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .row {
      position: relative;
    }

    .row::after {
      position: absolute;
      content: '';
      width: 1px;
      height: 40px;
      left: -28px;
      top: 5px;
      background-color: #f2f2f2;
    }

    .icon {
      display: inline-flex;
      justify-self: center;
      align-items: center;
      // width: 18px;
      height: 18px;
      padding: 0 3px;
      margin-right: 4px;
      font-size: 12px;
      color: #fff;
      background-color: #01c68b;
    }

    .textt {
      line-height: 22px;
      font-size: 14px;
      color: #858585;
    }

    .textb {
      display: inline-flex;
      justify-self: center;
      align-items: center;
      margin-top: 4px;
      line-height: 24px;
      font-size: 16px;
      color: #242424;
    }
  }

  .other-wrap {
    position: relative;
    height: calc(100vh - 654rpx);
    margin: 16px;
    padding: 16px;
    background: #fff;
    border-radius: 10px;
    overflow-y: auto;

    .tilte {
      margin-bottom: 2px;
      line-height: 24px;
      font-size: 16px;
      color: #000;
    }

    .row-wrap {
      display: flex;
      justify-content: space-between;
      margin: 6px 0;
      color: #545454;

      .text {
        flex: 1;
        line-height: 22px;
        font-size: 14px;
      }

      .textl {
        color: $uni-color-primary;
      }

      .textr {
        text-align: right;
      }

      .textr1 {
        font-size: 12px;
        color: #b5b5b5;
        text-decoration: line-through;
      }

      .iconfont {
        margin-right: 6px;
        font-size: 16px;
        color: #000;
      }
    }
  }

  .bottom-wrap {
    display: flex;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    width: calc(100% - 32px);
    padding: 9px 16px;
    background-color: #fff;
    font-size: 14px;
    color: #242424;
    border-top: 1px solid #e6e6e6;

    .text-wrap {
      display: flex;
      align-items: center;
      height: 44px;
    }

    .text {
      font-size: 20px;
      color: #fa3939;
    }

    .bnt {
      width: 136px;
      height: 44px;
      margin: 0;
      border-radius: 50px;
      font-size: 16px;
    }
  }
}
</style>